package com.fengye.security.captcha.filter.security;

import com.fengye.security.captcha.filter.filter.VerificationCodeFilter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 *
 * @author sky
 * @date 2021年06月01日 9:34 上午
 */
@EnableWebSecurity(debug = true)
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/api/**").hasAnyAuthority("ROLE_ADMIN") // 必须拥有"ROLE_ADMIN"的权限
                .antMatchers("/user/api/**").hasRole("USER") // 必须拥有"USER"的角色
                .antMatchers("/app/api/**", "/captcha.jpg").permitAll() // 不需要认证
                .anyRequest().authenticated() // 其他的端点都必须登录认证
                .and()
                .csrf().disable() // 关闭 csrf 校验
                .formLogin()
                .loginPage("/myLogin.html")
                .loginProcessingUrl("/auth/form")
                .failureHandler(new MyAuthenticationFailureHandler())
                .permitAll() // 开启 form 登录
                .and()
                .addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class)
                .sessionManagement()
                .maximumSessions(1); // 同时在线人数为 1
    }
}
